package org.hsieh.tr.explore.ui.actions.dbview;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Event;
import org.hsieh.tr.explore.dbsource.ITableEntity;
import org.hsieh.tr.explore.exception.ExceptionHandler;
import org.hsieh.tr.explore.ui.console.TextResultConsole;
import org.hsieh.tr.explore.util.JFaceUtil;

public class DescripeTableAction extends AbstractViewActionDelegate {

    public static final String ID = "org.hsieh.tr.explore.action.DescripeTableAction";
    private ITableEntity table;

    @Override
    public void selectionChanged(IAction action, ISelection selection) {
	table = JFaceUtil.getFristSelected(selection, ITableEntity.class);
    }

    @Override
    public void runWithEvent(IAction action, Event event) {
	if (table != null) {
	    try {
		ResultSet columns = table.getMetaData().getColumns(
			table.getSchema().getTableCatalog(),
			table.getSchema().getName(), table.getName(), null);
		while (columns.next()) {
		    ResultSetMetaData rs = columns.getMetaData();
		    if (rs.getColumnCount() <= 0) {
			//
		    } else {
			for (int i = 1; i < rs.getColumnCount(); i++) {
			    rs.getColumnName(i);
			    rs.getColumnType(i);
			    rs.getColumnTypeName(i);
			    rs.getColumnClassName(i);
			    rs.getColumnDisplaySize(i);
			    rs.getColumnLabel(i);
			    rs.getPrecision(i);
			    rs.getScale(i);
			}
		    }
		}
	    } catch (SQLException e) {
		ExceptionHandler.prompt(getPart().getSite().getShell(), e);
	    }
	    TextResultConsole.console("Table:" + table.getName());
	}
    }
}
